﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.CompositeUI.Utility;

namespace Microsoft.Practices.CompositeUI.Collections
{
    /// <summary>
    /// 	A dictionary of lists.
    /// </summary>
    /// <typeparam name = "TKey">The key to use for lists.</typeparam>
    /// <typeparam name = "TValue">The type of the value held by lists.</typeparam>
    public class ListDictionary<TKey, TValue> : IDictionary<TKey, List<TValue>>
    {
        #region Fields & Properties

        private readonly Dictionary<TKey, List<TValue>> _innerDictionary = new Dictionary<TKey, List<TValue>>();

        /// <summary>
        /// 	Gets a shallow copy of all values in all lists.
        /// </summary>
        public List<TValue> Values
        {
            get
            {
                return _innerDictionary.Values.SelectMany(list => list).ToList();
            }
        }

        #endregion

        #region Implementation of IEnumerable

        /// <summary>
        /// 	Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// 	A <see cref = "T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        IEnumerator<KeyValuePair<TKey, List<TValue>>> IEnumerable<KeyValuePair<TKey, List<TValue>>>.GetEnumerator()
        {
            return _innerDictionary.GetEnumerator();
        }

        /// <summary>
        /// 	Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// 	An <see cref = "T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _innerDictionary.GetEnumerator();
        }

        #endregion

        #region Implementation of ICollection<KeyValuePair<TKey,List<TValue>>>

        /// <summary>
        /// 	Adds an item to the <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </summary>
        /// <param name = "item">The object to add to the <see cref = "T:System.Collections.Generic.ICollection`1" />.</param>
        /// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
        void ICollection<KeyValuePair<TKey, List<TValue>>>.Add(KeyValuePair<TKey, List<TValue>> item)
        {
            ((ICollection<KeyValuePair<TKey, List<TValue>>>) _innerDictionary).Add(item);
        }

        /// <summary>
        /// 	Removes all items from the <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </summary>
        /// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.Generic.ICollection`1" /> is read-only. </exception>
        public void Clear()
        {
            _innerDictionary.Clear();
        }

        /// <summary>
        /// 	Determines whether the <see cref = "T:System.Collections.Generic.ICollection`1" /> contains a specific value.
        /// </summary>
        /// <returns>
        /// 	true if <paramref name = "item" /> is found in the <see cref = "T:System.Collections.Generic.ICollection`1" />; otherwise, false.
        /// </returns>
        /// <param name = "item">The object to locate in the <see cref = "T:System.Collections.Generic.ICollection`1" />.</param>
        bool ICollection<KeyValuePair<TKey, List<TValue>>>.Contains(KeyValuePair<TKey, List<TValue>> item)
        {
            return ((ICollection<KeyValuePair<TKey, List<TValue>>>) _innerDictionary).Contains(item);
        }

        /// <summary>
        /// 	Copies the elements of the <see cref = "T:System.Collections.Generic.ICollection`1" /> to an <see
        ///  	cref = "T:System.Array" />, starting at a particular <see cref = "T:System.Array" /> index.
        /// </summary>
        /// <param name = "array">The one-dimensional <see cref = "T:System.Array" /> that is the destination of the elements copied from <see
        ///  	cref = "T:System.Collections.Generic.ICollection`1" />. The <see cref = "T:System.Array" /> must have zero-based indexing.</param>
        /// <param name = "arrayIndex">The zero-based index in <paramref name = "array" /> at which copying begins.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "array" /> is null.</exception>
        /// <exception cref = "T:System.ArgumentOutOfRangeException"><paramref name = "arrayIndex" /> is less than 0.</exception>
        /// <exception cref = "T:System.ArgumentException"><paramref name = "array" /> is multidimensional.-or-The number of elements in the source <see
        ///  	cref = "T:System.Collections.Generic.ICollection`1" /> is greater than the available space from <paramref
        ///  	name = "arrayIndex" /> to the end of the destination <paramref name = "array" />.-or-Type cannot be cast automatically to the type of the destination <paramref
        ///  	name = "array" />.</exception>
        void ICollection<KeyValuePair<TKey, List<TValue>>>.CopyTo(KeyValuePair<TKey, List<TValue>>[] array, int arrayIndex)
        {
            ((ICollection<KeyValuePair<TKey, List<TValue>>>) _innerDictionary).CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// 	Removes the first occurrence of a specific object from the <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </summary>
        /// <returns>
        /// 	true if <paramref name = "item" /> was successfully removed from the <see
        ///  	cref = "T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref
        ///  	name = "item" /> is not found in the original <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </returns>
        /// <param name = "item">The object to remove from the <see cref = "T:System.Collections.Generic.ICollection`1" />.</param>
        /// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
        bool ICollection<KeyValuePair<TKey, List<TValue>>>.Remove(KeyValuePair<TKey, List<TValue>> item)
        {
            return ((ICollection<KeyValuePair<TKey, List<TValue>>>) _innerDictionary).Remove(item);
        }

        /// <summary>
        /// 	Gets the number of elements contained in the <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </summary>
        /// <returns>
        /// 	The number of elements contained in the <see cref = "T:System.Collections.Generic.ICollection`1" />.
        /// </returns>
        public int Count
        {
            get
            {
                return _innerDictionary.Count;
            }
        }

        /// <summary>
        /// 	Gets a value indicating whether the <see cref = "T:System.Collections.Generic.ICollection`1" /> is read-only.
        /// </summary>
        /// <returns>
        /// 	true if the <see cref = "T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.
        /// </returns>
        bool ICollection<KeyValuePair<TKey, List<TValue>>>.IsReadOnly
        {
            get
            {
                return ((ICollection<KeyValuePair<TKey, List<TValue>>>) _innerDictionary).IsReadOnly;
            }
        }

        #endregion

        #region Implementation of IDictionary<TKey,List<TValue>>

        /// <summary>
        /// 	Determines whether the <see cref = "T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key.
        /// </summary>
        /// <returns>
        /// 	true if the <see cref = "T:System.Collections.Generic.IDictionary`2" /> contains an element with the key; otherwise, false.
        /// </returns>
        /// <param name = "key">The key to locate in the <see cref = "T:System.Collections.Generic.IDictionary`2" />.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "key" /> is null.</exception>
        public bool ContainsKey(TKey key)
        {
            Guard.ArgumentNotNull(key, "key");
            return _innerDictionary.ContainsKey(key);
        }

        /// <summary>
        /// 	Adds an element with the provided key and value to the <see cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </summary>
        /// <param name = "key">The object to use as the key of the element to add.</param>
        /// <param name = "value">The object to use as the value of the element to add.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "key" /> is null.</exception>
        /// <exception cref = "T:System.ArgumentException">An element with the same key already exists in the <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" />.</exception>
        /// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception>
        void IDictionary<TKey, List<TValue>>.Add(TKey key, List<TValue> value)
        {
            Guard.ArgumentNotNull(key, "key");
            Guard.ArgumentNotNull(value, "value");
            _innerDictionary.Add(key, value);
        }

        /// <summary>
        /// 	Removes the element with the specified key from the <see cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </summary>
        /// <returns>
        /// 	true if the element is successfully removed; otherwise, false.  This method also returns false if <paramref
        ///  	name = "key" /> was not found in the original <see cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </returns>
        /// <param name = "key">The key of the element to remove.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "key" /> is null.</exception>
        /// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception>
        public bool Remove(TKey key)
        {
            Guard.ArgumentNotNull(key, "key");
            return _innerDictionary.Remove(key);
        }

        /// <summary>
        /// 	Gets the value associated with the specified key.
        /// </summary>
        /// <returns>
        /// 	true if the object that implements <see cref = "T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key; otherwise, false.
        /// </returns>
        /// <param name = "key">The key whose value to get.</param>
        /// <param name = "value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref
        ///  	name = "value" /> parameter. This parameter is passed uninitialized.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "key" /> is null.</exception>
        bool IDictionary<TKey, List<TValue>>.TryGetValue(TKey key, out List<TValue> value)
        {
            value = this[key];
            return true;
        }

        /// <summary>
        /// 	Gets or sets the element with the specified key.
        /// </summary>
        /// <returns>
        /// 	The element with the specified key.
        /// </returns>
        /// <param name = "key">The key of the element to get or set.</param>
        /// <exception cref = "T:System.ArgumentNullException"><paramref name = "key" /> is null.</exception>
        /// <exception cref = "T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref
        ///  	name = "key" /> is not found.</exception>
        /// <exception cref = "T:System.NotSupportedException">The property is set and the <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception>
        public List<TValue> this[TKey key]
        {
            get
            {
                if (!_innerDictionary.ContainsKey(key))
                {
                    _innerDictionary.Add(key, new List<TValue>());
                }
                return _innerDictionary[key];
            }
            set
            {
                _innerDictionary[key] = value;
            }
        }

        /// <summary>
        /// 	Gets an <see cref = "T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </summary>
        /// <returns>
        /// 	An <see cref = "T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </returns>
        public ICollection<TKey> Keys
        {
            get
            {
                return _innerDictionary.Keys;
            }
        }

        /// <summary>
        /// 	Gets an <see cref = "T:System.Collections.Generic.ICollection`1" /> containing the values in the <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </summary>
        /// <returns>
        /// 	An <see cref = "T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see
        ///  	cref = "T:System.Collections.Generic.IDictionary`2" />.
        /// </returns>
        ICollection<List<TValue>> IDictionary<TKey, List<TValue>>.Values
        {
            get
            {
                return _innerDictionary.Values;
            }
        }

        #endregion

        #region Add

        /// <summary>
        /// 	If a list does not already exist, it will be created automatically.
        /// </summary>
        /// <param name = "key">The key of the list that will hold the value.</param>
        public void Add(TKey key)
        {
            Guard.ArgumentNotNull(key, "key");
            CreateNewList(key);
        }

        /// <summary>
        /// 	Adds a value to a list with the given key. If a list does not already exist, 
        /// 	it will be created automatically.
        /// </summary>
        /// <param name = "key">The key of the list that will hold the value.</param>
        /// <param name = "value">The value to add to the list under the given key.</param>
        public void Add(TKey key, TValue value)
        {
            Guard.ArgumentNotNull(key, "key");
            Guard.ArgumentNotNull(value, "value");
            if (_innerDictionary.ContainsKey(key))
            {
                _innerDictionary[key].Add(value);
            }
            else
            {
                var values = CreateNewList(key);
                values.Add(value);
            }
        }

        #region Create New List

        private List<TValue> CreateNewList(TKey key)
        {
            var values = new List<TValue>();
            _innerDictionary.Add(key, values);
            return values;
        }

        #endregion

        #endregion

        #region Contains

        /// <summary>
        /// 	Determines whether the dictionary contains the specified value.
        /// </summary>
        /// <param name = "value">The value to locate.</param>
        /// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns>
        public bool ContainsValue(TValue value)
        {
            return _innerDictionary.Any(pair => pair.Value.Contains(value));
        }

        #endregion

        #region Find

        /// <summary>
        /// 	Retrieves the all the elements from the list which have a key that matches the condition 
        /// 	defined by the specified predicate.
        /// </summary>
        /// <param name = "keyFilter">The filter with the condition to use to filter lists by their key.</param>
        /// <returns></returns>
        public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter)
        {
            return _innerDictionary.Where(pair => keyFilter(pair.Key)).SelectMany(pair => pair.Value);
        }

        /// <summary>
        /// 	Retrieves all the elements that match the condition defined by the specified predicate.
        /// </summary>
        /// <param name = "valueFilter">The filter with the condition to use to filter values.</param>
        /// <returns></returns>
        public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter)
        {
            return _innerDictionary.SelectMany(pair => pair.Value.Where(value => valueFilter(value)));
        }

        #endregion

        #region Remove

        /// <summary>
        /// 	Removes a value from the list with the given key.
        /// </summary>
        /// <param name = "key">The key of the list where the value exists.</param>
        /// <param name = "value">The value to remove.</param>
        public void Remove(TKey key, TValue value)
        {
            Guard.ArgumentNotNull(key, "key");
            Guard.ArgumentNotNull(value, "value");
            if (_innerDictionary.ContainsKey(key))
            {
                _innerDictionary[key].RemoveAll(item => value.Equals(item));
            }
        }

        /// <summary>
        /// 	Removes a value from all lists where it may be found.
        /// </summary>
        /// <param name = "value">The value to remove.</param>
        public void Remove(TValue value)
        {
            foreach (var pair in _innerDictionary)
            {
                Remove(pair.Key, value);
            }
        }

        #endregion
    }
}